/*
 * LibraryStudyView.java
 */

package librarystudy;

import java.awt.Dimension;
import javax.swing.event.TableModelListener;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.AbstractTableModel;
import librarystudy.data.ATag;
import librarystudy.data.Book;

/**
 * The application's main frame.
 */
public class LibraryStudyView extends FrameView {

    public LibraryStudyView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

        JFrame mainFrame = LibraryStudyApp.getApplication().
                getMainFrame();
        mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        mainFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("We're closing!  WOOO!!");
                quit();
//                int returnValue =
//                        javax.swing.JOptionPane.showConfirmDialog(
//                        mainPanel,
//                        "Are you sure you want to quit?",
//                        "Confirmation",
//                        javax.swing.JOptionPane.YES_NO_OPTION,
//                        javax.swing.JOptionPane.INFORMATION_MESSAGE);
//                if (returnValue == javax.swing.JOptionPane.YES_OPTION) {
//                    quit();
//                }
            }
        });
    }

    DropDownTableModel dropDownTableModel;
    JScrollPane scrollPane;

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = LibraryStudyApp.getApplication().getMainFrame();
            aboutBox = new LibraryStudyAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        LibraryStudyApp.getApplication().show(aboutBox);
    }

    @Action
    public void quit() {
        System.out.println("I got called!");
        LibraryStudyApp.closeDatabase();
        System.exit(0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        titleField = new javax.swing.JTextField();
        authorField = new javax.swing.JTextField();
        dateField = new javax.swing.JTextField();
        tagsField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        descTextArea = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        saveButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(librarystudy.LibraryStudyApp.class).getContext().getResourceMap(LibraryStudyView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        titleField.setText(resourceMap.getString("titleField.text")); // NOI18N
        titleField.setName("titleField"); // NOI18N
        titleField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textFieldFocusLost(evt);
            }
        });
        titleField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                titleFieldKeyTyped(evt);
            }
        });

        authorField.setText(resourceMap.getString("authorField.text")); // NOI18N
        authorField.setName("authorField"); // NOI18N
        authorField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textFieldFocusLost(evt);
            }
        });
        authorField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                authorFieldKeyTyped(evt);
            }
        });

        dateField.setText(resourceMap.getString("dateField.text")); // NOI18N
        dateField.setName("dateField"); // NOI18N

        tagsField.setText(resourceMap.getString("tagsField.text")); // NOI18N
        tagsField.setName("tagsField"); // NOI18N
        tagsField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textFieldFocusLost(evt);
            }
        });
        tagsField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tagsFieldKeyTyped(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        descTextArea.setColumns(20);
        descTextArea.setRows(5);
        descTextArea.setName("descTextArea"); // NOI18N
        jScrollPane1.setViewportView(descTextArea);

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(titleField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE))
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(authorField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(dateField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE))
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(tagsField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE))
                    .add(jLabel5))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel1)
                    .add(titleField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(authorField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(dateField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(tagsField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(librarystudy.LibraryStudyApp.class).getContext().getActionMap(LibraryStudyView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        menuBar.add(jMenu1);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveButtonMouseClicked(evt);
            }
        });

        resetButton.setText(resourceMap.getString("resetButton.text")); // NOI18N
        resetButton.setName("resetButton"); // NOI18N
        resetButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resetButtonMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(saveButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(resetButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 104, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(saveButton)
                    .add(resetButton))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void resetButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resetButtonMouseClicked
        authorField.setText("");
        dateField.setText("");
        descTextArea.setText("");
        tagsField.setText("");
        titleField.setText("");

        LibraryStudyApp.dumpAllBooks();
}//GEN-LAST:event_resetButtonMouseClicked

    private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked
        Book newBook = new Book();

        newBook.setAuthorName(authorField.getText());
        newBook.setTitle(titleField.getText());
        newBook.setDescription(descTextArea.getText());

        try {
            DateFormat format = new SimpleDateFormat("yyyy");
            newBook.setPublicationDate(format.parse(dateField.getText()));           
        } catch (ParseException pe0) {
            try {
                DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
                newBook.setPublicationDate(format.parse(dateField.getText()));
            } catch (ParseException pe) {
                try {
                    DateFormat format = new SimpleDateFormat("yyyy-MMM-dd");
                    newBook.setPublicationDate(format.parse(dateField.getText()));
                } catch (ParseException pe2) {
                    try {
                        DateFormat format = new SimpleDateFormat("M/d/yyyy");
                        newBook.setPublicationDate(format.parse(dateField.getText()));
                    } catch (ParseException pe3) {
                        throw new IllegalArgumentException("Error parsing date.");
                    }
                }
           }
        }

        newBook.addTagsFromSpaceDelimitedString(tagsField.getText());

        LibraryStudyApp.addBook(newBook);

        JOptionPane.showMessageDialog(evt.getComponent(), "Saved!", "What?", JOptionPane.INFORMATION_MESSAGE);
        resetButtonMouseClicked(evt);
    }//GEN-LAST:event_saveButtonMouseClicked

    private void titleFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_titleFieldKeyTyped
        // Find as you type
        int originalCaretPosition = titleField.getCaretPosition();

        ArrayList<Book> listOfMatches =
                (ArrayList) LibraryStudyApp.findTitleAsYouType(titleField.getText() +
                (Character.isLetterOrDigit(evt.getKeyChar()) ? Character.toString(evt.getKeyChar()) : ""));

        ArrayList<String> rowData = new ArrayList<String>();

        Iterator i = listOfMatches.iterator();
        while (i.hasNext()) {
            Book newBook = (Book)i.next();
            rowData.add(newBook.getTitle());
        }

        if (rowData.size() > 0){
            dropDownTableModel = new DropDownTableModel(rowData, listOfMatches);
            final JTable table = new JTable(dropDownTableModel);
            table.setPreferredScrollableViewportSize(new Dimension(250, 70));

            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Object o = dropDownTableModel.getDropDownObjectForIndex(table.rowAtPoint(e.getPoint()));
                    if (o instanceof Book) {

                        mainPanel.remove(scrollPane);
                        mainPanel.validate();
                        mainPanel.repaint();
                        scrollPane = null;

                        titleField.setText(((Book)o).getTitle());
//                        titleField.setCaretPosition(originalCaretPosition);
                        authorField.setText(((Book)o).getAuthorFormattedName());
                        dateField.setText(((Book)o).getPublicationDateAsPrettyString());
                        tagsField.setText(((Book)o).getTagsAsSpaceDelimitedString());
                        descTextArea.setText(((Book)o).getDescString());
                    }
                }
            });

        //Create the scroll pane and add the table to it.
            if (scrollPane == null) {
                scrollPane = new JScrollPane(table);
                scrollPane.setLocation(titleField.getLocation().x,
                        titleField.getLocation().y + titleField.getHeight());
                scrollPane.setSize(new Dimension(250, 70));
                table.setFocusable(false);
                scrollPane.setFocusable(false);
                mainPanel.add(scrollPane);
                mainPanel.validate();
                scrollPane.setVisible(true);
            }
        } else if (scrollPane != null) {
            mainPanel.remove(scrollPane);
            mainPanel.validate();
            mainPanel.repaint();
            scrollPane = null;
        }
    }//GEN-LAST:event_titleFieldKeyTyped

    private void textFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textFieldFocusLost
        if (scrollPane != null) {
            mainPanel.remove(scrollPane);
            mainPanel.validate();
            mainPanel.repaint();
            scrollPane = null;
        }
}//GEN-LAST:event_textFieldFocusLost

    private void authorFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_authorFieldKeyTyped
    ArrayList<Book> listOfMatches =
                (ArrayList) LibraryStudyApp.findAuthorAsYouType(authorField.getText() +
                (Character.isLetterOrDigit(evt.getKeyChar()) ? Character.toString(evt.getKeyChar()) : ""));

        ArrayList<String> rowData = new ArrayList<String>();

        Iterator i = listOfMatches.iterator();
        while (i.hasNext()) {
            Book newBook = (Book)i.next();
            rowData.add(newBook.getAuthorFormattedName());
        }

        if (rowData.size() > 0){
            dropDownTableModel = new DropDownTableModel(rowData, listOfMatches);
            final JTable table = new JTable(dropDownTableModel);
            table.setPreferredScrollableViewportSize(new Dimension(250, 70));

            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Object o = dropDownTableModel.getDropDownObjectForIndex(table.rowAtPoint(e.getPoint()));
                    if (o instanceof Book) {

                        mainPanel.remove(scrollPane);
                        mainPanel.validate();
                        mainPanel.repaint();
                        scrollPane = null;

                        titleField.setText(((Book)o).getTitle());
//                        titleField.setCaretPosition(originalCaretPosition);
                        authorField.setText(((Book)o).getAuthorFormattedName());
                        dateField.setText(((Book)o).getPublicationDateAsPrettyString());
                        tagsField.setText(((Book)o).getTagsAsSpaceDelimitedString());
                        descTextArea.setText(((Book)o).getDescString());
                    }
                }
            });

        //Create the scroll pane and add the table to it.
            if (scrollPane == null) {
                scrollPane = new JScrollPane(table);
                scrollPane.setLocation(authorField.getLocation().x,
                        authorField.getLocation().y + authorField.getHeight());
                scrollPane.setSize(new Dimension(250, 70));
                table.setFocusable(false);
                scrollPane.setFocusable(false);
                mainPanel.add(scrollPane);
                mainPanel.validate();
                scrollPane.setVisible(true);
            }
        } else if (scrollPane != null) {
            mainPanel.remove(scrollPane);
            mainPanel.validate();
            mainPanel.repaint();
            scrollPane = null;
        }
    }//GEN-LAST:event_authorFieldKeyTyped

    private void tagsFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tagsFieldKeyTyped
       // Todo implement the tags as you type.
        ArrayList<ATag> listOfMatches =
                (ArrayList) LibraryStudyApp.findTagAsYouType(tagsField.getText() +
                (Character.isLetterOrDigit(evt.getKeyChar()) ? Character.toString(evt.getKeyChar()) : ""));

        ArrayList<String> rowData = new ArrayList<String>();

        Iterator i = listOfMatches.iterator();
        while (i.hasNext()) {
            ATag newBook = (ATag)i.next();
            rowData.add(newBook.getTagName());
        }

        if (rowData.size() > 0){
            dropDownTableModel = new DropDownTableModel(rowData, listOfMatches);
            final JTable table = new JTable(dropDownTableModel);
            table.setPreferredScrollableViewportSize(new Dimension(250, 70));

            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Object o = dropDownTableModel.getDropDownObjectForIndex(table.rowAtPoint(e.getPoint()));
                    if (o instanceof ATag) {

                        System.out.println(((ATag)o).getTagName());
                    }
                }
            });

        //Create the scroll pane and add the table to it.
            if (scrollPane == null) {
                scrollPane = new JScrollPane(table);
                scrollPane.setLocation(authorField.getLocation().x,
                        authorField.getLocation().y + authorField.getHeight());
                scrollPane.setSize(new Dimension(250, 70));
                table.setFocusable(false);
                scrollPane.setFocusable(false);
                mainPanel.add(scrollPane);
                mainPanel.validate();
                scrollPane.setVisible(true);
            }
        } else if (scrollPane != null) {
            mainPanel.remove(scrollPane);
            mainPanel.validate();
            mainPanel.repaint();
            scrollPane = null;
        }
    }//GEN-LAST:event_tagsFieldKeyTyped

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
        JDialog dialog = new JDialog();
        QuizView qv = new QuizView();
        dialog.setBounds(0, 0, 400, 300);
        dialog.add(qv);
        dialog.setVisible(true);
        qv.setVisible(true);

    }//GEN-LAST:event_jMenu1MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField authorField;
    private javax.swing.JTextField dateField;
    private javax.swing.JTextArea descTextArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField tagsField;
    private javax.swing.JTextField titleField;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;


    private class DropDownTableModel extends AbstractTableModel {
        private ArrayList<String> myData;
        private ArrayList listOfBooks;  // Either typed Book or Tag

        public DropDownTableModel(ArrayList d, ArrayList b) {
            myData = d;
            listOfBooks = b;
        }

        public void setData(ArrayList a) {
            myData = a;
        }

        public Object getDropDownObjectForIndex(int index) {
            return listOfBooks.get(index);
        }
        
        public int getRowCount() {
            return myData.size();
        }

        public int getColumnCount() {
            return 1;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return null;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
        
        public Object getValueAt(int rowIndex, int columnIndex) {
            return myData.get(rowIndex);
        }
        
        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void addTableModelListener(TableModelListener l) {
            super.addTableModelListener(l);
        }

        @Override
        public void removeTableModelListener(TableModelListener l) {
            super.removeTableModelListener(l);
        }
    }

}
